package com.javaee.ejb.session;

import java.util.List;

import com.javaee.ejb.entity.ConversationMessage;
import com.javaee.ejb.session.remote.ConversationMessageManagerRemote;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class MessageManager
 */
@Stateless
public class ConversationMessageManager implements
		ConversationMessageManagerRemote {

	@PersistenceContext
	private EntityManager entityManager;

	public ConversationMessageManager() {
	}

	public int saveConversationMessage(ConversationMessage conversationMessage) {
		conversationMessage = entityManager.merge(conversationMessage);
		entityManager.persist(conversationMessage);
		return conversationMessage.getId();
	}

	@SuppressWarnings("unchecked")
	public List<ConversationMessage> getListByConversationId(int conversationId) {
		Query query = entityManager
				.createQuery("SELECT DISTINCT message FROM ConversationMessage message INNER JOIN message.Conversation conversation WHERE conversation.id = :conversationId ORDER BY message.time DESC");
		query.setParameter("conversationId", conversationId);

		return (List<ConversationMessage>) query.getResultList();
	}

}